namespace SimpleWebServices.Security.Principal
{
    using System;
    using System.Collections.Specialized;
    using System.Web;
    using System.Xml.Serialization;
    using SimpleWebServices.Data;
    using SimpleWebServices.Web;

    [XmlRoot("authentication")]
    public sealed class AuthenticationRecord<T> : AuthenticationRecord
        where T : User
    {
        [XmlIgnore]
        public override string Entity
        {
            get
            {
                Entity value = new Entity(base.Entity);
                value.Append(this.User);

                return value;
            }
        }

        [XmlElement("user")]
        public Link<T> User
        {
            get;
            set;
        }

        public HttpCookie ToHttpCookie(bool session)
        {
            NameValueCollection variables = HttpContextFactory.Current.Request.ServerVariables;
            this.Data["ip"] =
                variables["HTTP_X_FORWARDED_FOR"]
                ?? variables["REMOTE_ADDR"]
                ?? HttpContextFactory.Current.Request.UserHostAddress;

            this.Expires = session ? DateTime.MinValue : DateTimeFactory.UtcNow.AddDays(1);
            this.Store();

            return new HttpCookie("Authentication", this.Urn)
            {
                Expires = this.Expires,
                HttpOnly = false
            };
        }

        public void Store()
        {
            if (null == this.Urn)
            {
                this.Urn = AuthenticationRecord.FormatUrn(Guid.NewGuid());
            }

            this.Store<AuthenticationRecord<T>>();
        }
    }
}